import {
    AccessToken,
    LoginManager,
    GraphRequest,
    GraphRequestManager
} from 'react-native-fbsdk';

const _scopes = [
    `email`,
    `public_profile`
] as Array<string>;

interface Info {
    birthday: string,
    name: string,
    email: string,
    gender: string,

}

interface Res extends Info {
    token: string,
    userId: string,
    avatar: string
}

const _getAvatar = (userId: string): string => (
    `http://graph.facebook.com/${userId}/picture?width=960&height=960`
)

const getUserInfo = (token?: string) => (
    new Promise((resolve, reject) => {
        const fields = [
            `birthday`,
            `name`,
            `email`,
            `gender`
        ] as Array<string>;
        const _para = {
            fields: {
                string: fields.join(`,`)
            }
        }
        const _config = {
            parameters: _para,
            accessToken: token
        }
        const _args = [`/me`, _config, (error, res): void => (
            !error ? resolve(res) : reject({message: error})
        )]
        const request = new GraphRequest(..._args)
        new GraphRequestManager().addRequest(request).start();
    })
)


export default async (): Promise<Res> => {
    try {
        const {
            isCancelled
        } = await LoginManager.logInWithPermissions(_scopes);

        if (isCancelled) {
            return Promise.reject({
                message: `Login Cancel.`
            })
        }

        const {
            userID,
            accessToken
        } = await AccessToken.getCurrentAccessToken();

        const info: Info = await getUserInfo(accessToken);

        return {
            ...info,
            userId: userID,
            token: accessToken,
            avatar: _getAvatar(userID)
        }
    }
    catch (e) {
        return Promise.reject({
            message: e.message || `Login Error.`
        })
    }
}